import axios from "./http";
import gps from "../utils/gps";
import utils from "../utils/utils";
const server_10085 = "http://47.92.107.19:10085/";

const params = {
  cityDistrict: 2,
  stateStation: 11,
  province: "河北省"
};

const getDistrictByCondition = (params, callback) => {
  axios
    .post(server_10085 + "district/findDistrictByCondition", params)
    .then(res => {
      callback(res.data.success ? res.data.data : {});
    });
};

export function getCityDistrict(callback) {
  getDistrictByCondition(
    {
      districtId: params.cityDistrict,
      type: params.cityDistrict
    },
    callback
  );
}

export function getStateStationRealtime(callback) {
  getStateStationRealtimeByCondition(
    {
      districtId: params.cityDistrict,
      type: params.stateStation,
      province: params.province
    },
    callback
  );
}

const getStateStationRealtimeByCondition = (params, callback) => {
  axios
    .all([
      axios.get(
        "http://nairp.market.alicloudapi.com/api/v1/nation_air_by_province/station_realtime_list",
        {
          params,
          headers: {
            Authorization: "APPCODE c0079e076f774abd8b82dbbaf30e0eb6"
          }
        }
      ),
      axios.post(server_10085 + "device/findDeviceListByCondition", params)
    ])
    .then(res => {
      let array = formatterStateStationRealtime(res[0].data, res[1].data);
      callback(array);
    });
};

export function formatterStateStationRealtime(data1, data2) {
  if (!data1.success || !data2.success) {
    return [];
  }
  let array1 = [].concat.apply([], data1.data);
  let array2 = Array.from(data2.data);
  let array3 = array1.filter(item1 => {
    return array2.some(item2 => {
      if (item1.station_code === item2.deviceId) {
        let wgs = gps.bd09ToWgs84(item2.lat, item2.lng);
        item1.longitude = wgs.lng;
        item1.latitude = wgs.lat;
        return true;
      }
    });
  });
  return array3.sort(utils.compare(["aqi"], 0));
}
